package com.flca.frw.zk.validate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zul.Constraint;

import com.flca.frw.validators.ValidationError;
import com.flca.frw.validators.Validator;

public class ValidateNumber implements Constraint {

	private boolean req;
	private Integer minInt;
	private Integer maxInt;
	
	public ValidateNumber(Object aMin, Object aMax, boolean aRequired) 
	{
		super();
		
		this.req = aRequired;
		
		if (aMin != null) {
			if (aMin instanceof Integer) {
				this.minInt = ((Integer) aMin).intValue();
			} else if (aMin instanceof Double) {
				this.minInt = ((Double) aMin).intValue();
			} else if (aMin instanceof BigDecimal) {
				this.minInt = ((BigDecimal) aMin).intValue();
			} else if (aMin instanceof Long) {
				this.minInt = ((Long) aMin).intValue();
			} 
		} 

		if (aMax != null) {
			if (aMax instanceof Integer) {
				this.maxInt = ((Integer) aMax).intValue();
			} else if (aMax instanceof Double) {
				this.maxInt = ((Double) aMax).intValue();
			} else if (aMax instanceof BigDecimal) {
				this.maxInt = ((BigDecimal) aMax).intValue();
			} else if (aMax instanceof Long) {
				this.maxInt = ((Long) aMax).intValue();
			} 
		} 

	}

	public void validate(Component aComp, Object aValue)
			throws WrongValueException 
	{
		if (aValue == null && req) {
			String msg = "Dit veld is verplicht"; 
			throw new WrongValueException(aComp, msg);
		} else if (aValue != null && aValue instanceof Integer) {
			validate(aComp, aValue, ((Integer) aValue).intValue());
		} else if (aValue != null && aValue instanceof BigDecimal) {
			validate(aComp, aValue, ((BigDecimal) aValue).intValue());
		} 
	}

	private void validate(Component aComp, Object aValue, int aTestVal) 
	{
		List<ValidationError> errors = new ArrayList<ValidationError>();
		
		if (minInt != null) {
			if (!Validator.testGreaterOrEquals(aTestVal, minInt.intValue(), errors, "", null)) {
				String msg = "Waarde te klein, minimum = " + minInt; 
				throw new WrongValueException(aComp, msg);
			}
		}
		
		if (maxInt != null) {
			if (!Validator.testSmallerOrEquals(aTestVal, maxInt.intValue(), errors, "", null)) {
				String msg = "Waarde te groot, maximum = " + maxInt; 
				throw new WrongValueException(aComp, msg);
			}
		}
	}

}
